import controller from '../core/controller'
import { get, post } from '../core/route'
import {login} from '../decorater/auth'
import { db, tran, id } from '../core/db/mysql/db'
import Query from '../core/db/mysql/query'
import i18n from "../core/i18n";
import Validator from "../core/validator";
import AuthValidator from "../validator/auth";

@controller()
export default class auth{

    @login
    @get('/auth')
    async index() {
        return await this.fetch('auth')
    }

    @login
    @get('/auth/list')
    async list() {
        try{
            return await db(async conn => {
                let QAuth = new Query(conn, 'sys_auth')
                this.params.name !== undefined && this.params.name !== '' && (QAuth.where('name', 'like', `%${this.params.name}%`))
                this.session.userid !== 1 && QAuth.where('adduser', this.session.userid)
                let records = await QAuth.page(this.params.page?this.params.page:1, 15, this.params)
                this.assign('records', records)
            }),this.setCode(0).setMsg(i18n.success).json()
        }catch(err) {
            return this.setCode(-500).setMsg(i18n.sys_err).json()
        }
    }

    @login
    @post('/auth/add')
    async add() {
        let validator = new Validator(AuthValidator);
        let res = await validator.check(this.params);
        if(res !== true) {
            return this.setCode(1).setMsg(res).json();
        }
        try {
            return await tran(async conn => {
                let QAuth = new Query(conn, 'sys_auth');
                const QAuthRecord = new Query(conn, 'sys_auth_record');
                const { authRecord = [] } = this.params;
                delete this.params.authRecord;
                await QAuth.insert({
                    ...this.params,
                    modifytime: new Date().getTime(),
                    modify: this.session.userid,
                    addtime: new Date().getTime(),
                    adduser: this.session.userid
                });
                let aid =  await id(conn);
                const authRecords = authRecord.map(vo => ({ auth_id: aid, menu_id: vo }));
                await QAuthRecord.insertAll(authRecords);
                this.assign('id', aid);
                return true;
            }) ? this.setCode(0).setMsg(i18n.success).json() : this.setCode(1).setMsg(i18n.sys_err).json();
        } catch(err) {
            console.log('error===>', err);
            return this.setCode(-500).setMsg(i18n.sys_err).json();
        }
    }

    @login
    @post('/auth/edit')
    async edit() {
        let validator = new Validator(AuthValidator);
        let res = await validator.check(this.params);
        if(res !== true) {
            return this.setCode(1).setMsg(res).json();
        }
        return await tran(async conn => {
            let QAuth = new Query(conn, 'sys_auth');
            const QAuthRecord = new Query(conn, 'sys_auth_record');
            const { authRecord } = this.params;
            delete this.params.authRecord;
            try{
                await QAuth.where('id', this.params.id).update({
                    ...this.params,
                    modifytime: new Date().getTime(),
                    modify: this.session.userid,
                });
                await QAuthRecord.where('auth_id', this.params.id).delete();
                const authRecords = authRecord.map(vo => ({ auth_id: this.params.id, menu_id: vo }));
                await QAuthRecord.insertAll(authRecords);
                return true
            }catch(err) {
                console.log(err)
                return false
            }
        })?this.setCode(0).setMsg(i18n.sys_success).json():this.setCode(1).setMsg(i18n.sys_err).json()
    }

    @login
    @post('/auth/del')
    async del() {
        let id = this.params.id
        let result =  await db(async conn => {
            let QAuth = new Query(conn, 'sys_auth');
            let QAuthRecord = new Query(conn, 'sys_user_auth');
            try{
                const records = await QAuthRecord.where('auth_id', this.params.id).select();
                if (records.length > 0) {
                  return {
                    success: false,
                    msg: '该权限有用户绑定，请先解除用户绑定权限',
                  }
                }
                await QAuth.where('id', id).delete();
                return {
                  success: true,
                  msg: '删除成功',
                }
            }catch(err) {
                return {
                  success: false,
                  msg: err,
                }
            }
        })
        return result.success ? this.setCode(0).setMsg(result.msg).json():this.setCode(1).setMsg(result.msg).json()
    }

    @login
    @get('/auth/getChecked')
    async getChecked() {
        const id = this.params.id;
        return await db(async conn => {
            let QAuthRecord = new Query(conn, 'sys_auth_record');
            try {
                const menu_ids = await QAuthRecord
                  .fields('menu_id')
                  .where('auth_id', id).select();
                const ids = menu_ids.map(vo => vo.menu_id);
                this.assign('ids', ids);
                return true;
            } catch(err) {
                console.log(err);
                return false;
            }
        }) ? this.setCode(0).setMsg(i18n.sys_success).json() : this.setCode(1).setMsg(i18n.sys_err).json();
    }

    @login
    @post('/auth/status')
    async status() {
        let id = this.params.id;
        return await db(async conn => {
          let QAuth = new Query(conn, 'sys_auth');
          try {
            const bool = QAuth.where('id', this.params.id).update({ status: this.params.status });
            return bool;
          } catch(err) {
            return false;
          }
        })?this.setCode(0).setMsg(i18n.sys_success).json():this.setCode(1).setMsg(i18n.sys_err).json();
    }
}
